package com.xxkj.drugtraceability.ui.patientlist

import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import androidx.lifecycle.Observer
import com.google.gson.Gson
import com.xxhis.refactor.eventbus.MessageCode
import com.xxkj.drugtraceability.R
import com.xxkj.drugtraceability.base.BaseVMActivity
import com.xxkj.drugtraceability.bean.AdviceRequest
import com.xxkj.drugtraceability.bean.BarcodeMessage
import com.xxkj.drugtraceability.bean.EventMessage
import com.xxkj.drugtraceability.databinding.ActivityPatientListBinding
import com.xxkj.drugtraceability.dialog.DepartPop
import com.xxkj.drugtraceability.dialog.YellowDialog
import com.xxkj.drugtraceability.ext.clickN
import com.xxkj.drugtraceability.ext.getSpValue
import com.xxkj.drugtraceability.lifecycle.KtxManager
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * author: zhoujingjin
 * created on: 2024/9/11 19:06
 * description:病人列表页面
 */
class PatientListActivity : BaseVMActivity() {
    private val binding by binding<ActivityPatientListBinding>(R.layout.activity_patient_list)
    private val viewModel by viewModel<PatientListViewModel>()
    private var departPop: DepartPop? = null
    private lateinit var inFragment: PatientFragment
    private lateinit var outFragment: PatientFragment
    private lateinit var currentFragment: PatientFragment
    override fun initView() {
        binding.apply {
            toolBar.title = ""
            setSupportActionBar(toolBar)
            toolBar.setNavigationOnClickListener {
                onBackPressed()
            }
            tvIn.isSelected = true
            tvIn.clickN {
                if (!tvIn.isSelected) {
                    tvIn.isSelected = true
                    tvOut.isSelected = false
                    viewModel.inState.postValue("01")
                }
            }
            tvOut.clickN {
                if (!tvOut.isSelected) {
                    tvIn.isSelected = false
                    tvOut.isSelected = true
                    viewModel.inState.postValue("02")
                }
            }
            flDepart.clickN {
                //显示全部科室
                departPop?.showAtLocation(llParent, Gravity.BOTTOM, 0, 0)
            }
            etInput.addTextChangedListener(object : TextWatcher {
                override fun afterTextChanged(s: Editable?) {
                    currentFragment.refreshData()
                }

                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int
                ) {
                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                }
            })
            inFragment = PatientFragment.newInstance("01")
            outFragment = PatientFragment.newInstance("02")
            currentFragment = inFragment
            supportFragmentManager.beginTransaction().add(R.id.container, inFragment)
                .add(R.id.container, outFragment).hide(outFragment).commit()
        }
    }

    fun getInputWord(): String {
        return binding.etInput.text.toString()
    }

    override fun initData() {
        viewModel.depart = getSpValue("deptId", "")
        viewModel.queryAllDept()
    }

    override fun startObserve() {
        viewModel.departList.observe(this, Observer { list ->
            if (!list.isNullOrEmpty()) {
                departPop = DepartPop(this, list) {
                    //筛选科室的病人
                    departPop?.dismiss()
                    binding.tvDepart.text = it.deptName
                    viewModel.departName.value = it.deptName
                    viewModel.depart = it.deptCode

                    inFragment.refreshData()
                    outFragment.refreshData()
                }
//                departPop?.showAtLocation(binding.llParent,Gravity.BOTTOM,0,0)
            }
        })
        viewModel.departName.observe(this, Observer {
            binding.tvDepart.text = it
        })
        viewModel.inState.observe(this, Observer { state ->
            if (state == "01") {
                currentFragment = inFragment
                supportFragmentManager.beginTransaction().hide(outFragment).show(inFragment)
                    .commit()
            } else if (state == "02") {
                currentFragment = outFragment
                supportFragmentManager.beginTransaction().hide(inFragment).show(outFragment)
                    .commit()
            }

        })
        viewModel.uiState.observe(this, Observer {
            if (!it.isError.isNullOrEmpty()) {
                YellowDialog(this, it.isError!!, 1) {}
            }
        })
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(message: EventMessage?) {
        message?.apply {
            //扫码拿到barcode了，去请求接口
            when (message.messageCode) {
                MessageCode.SCAN_BARCODE -> {
                    if (KtxManager.isTopActivity(this@PatientListActivity)) {
                        val barcodeMessage = this.any as BarcodeMessage
                        //调用扫药品的接口
                        viewModel.getDoctorOrderedInfoList(
                            barcodeMessage.barcode,
                            Gson().toJson(AdviceRequest("", "", barcodeMessage.barcode)),
                            this@PatientListActivity
                        )
                    }
                }
            }
        }
    }

    override fun onStart() {
        super.onStart()
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}